<template>
  <div class="article-list-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h2>文章列表</h2>
              <el-button type="primary" @click="goToCreateArticle" v-if="isAuthenticated">发表新文章</el-button>
            </div>
          </template>
          <el-table :data="articles" style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="标题">
              <template #default="scope">
                <div>
                  <router-link :to="`/articles/${scope.row.id}`">{{ scope.row.title }}</router-link>
                  <div class="article-meta-info">
                    <span class="meta-item"><span style="font-size:14px;">👍</span> {{ scope.row.likeCount || 0 }}</span>
                    <span class="meta-dot">·</span>
                    <span class="meta-item"><span style="font-size:14px;">💬</span> {{ scope.row.commentCount || 0 }}</span>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="author.username" label="作者" width="180">
              <template #default="scope">
                <el-avatar :src="scope.row.author?.avatar" :size="24" style="margin-right: 8px; background: #eee;">
                  {{ scope.row.author?.username ? scope.row.author.username.charAt(0).toUpperCase() : '' }}
                </el-avatar>
                <span>{{ scope.row.author?.username }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="发布时间" width="200">
              <template #default="scope">
                {{ new Date(scope.row.createdAt).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150" v-if="isAuthenticated">
              <template #default="scope">
                <el-button size="small" @click="editArticle(scope.row.id)" v-if="canEditOrDelete(scope.row.author.id)">编辑</el-button>
                <el-popconfirm title="确定删除这篇文章吗?" @confirm="deleteArticle(scope.row.id)">
                  <template #reference>
                    <el-button size="small" type="danger" v-if="canEditOrDelete(scope.row.author.id)">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalArticles"
            :page-size="pageSize"
            @current-change="handlePageChange"
            class="mt-4"
          >
          </el-pagination>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'ArticleList',
  setup() {
    const router = useRouter()
    const articles = ref([])
    const loading = ref(true)
    const totalArticles = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    const isAuthenticated = computed(() => !!localStorage.getItem('token'))
    const currentUser = computed(() => JSON.parse(localStorage.getItem('user') || '{}'))

    const fetchArticles = async (page = 1) => {
      loading.value = true
      try {
        const response = await axios.get(`/api/articles?current=${page}&size=${pageSize.value}`)
        articles.value = response.data.records
        totalArticles.value = response.data.total
        currentPage.value = page
      } catch (error) {
        ElMessage.error('获取文章列表失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    const handlePageChange = (page) => {
      fetchArticles(page)
    }

    const goToCreateArticle = () => {
      router.push('/articles/new')
    }

    const editArticle = (id) => {
      router.push(`/articles/edit/${id}`)
    }

    const deleteArticle = async (id) => {
      try {
        await axios.delete(`/api/articles/${id}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
        ElMessage.success('文章删除成功')
        fetchArticles(currentPage.value) // Refresh list
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '删除文章失败')
        console.error(error)
      }
    }

    const canEditOrDelete = (authorId) => {
        if (!isAuthenticated.value) return false;
        // Add admin role check if you have roles
        return currentUser.value.userId === authorId;
    };

    onMounted(() => {
      fetchArticles()
    })

    return {
      articles,
      loading,
      totalArticles,
      pageSize,
      isAuthenticated,
      fetchArticles,
      handlePageChange,
      goToCreateArticle,
      editArticle,
      deleteArticle,
      canEditOrDelete
    }
  }
}
</script>

<style scoped>
.article-list-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mt-4 {
  margin-top: 20px;
}

/* 文章标题样式 */
:deep(.el-table a) {
  font-family: "SimHei", "黑体", sans-serif;
  text-decoration: none;
  color: var(--macos-text);
  font-size: 16px;
  transition: color 0.3s ease;
}

:deep(.el-table a:hover) {
  color: var(--macos-accent);
}

:deep(.el-table .cell) {
  padding: 12px 0;
}

.article-meta-info {
  color: #999;
  font-size: 12px;
  margin-top: 2px;
  display: flex;
  align-items: center;
}
.meta-item {
  margin-right: 4px;
}
.meta-dot {
  margin: 0 4px;
  color: #ccc;
}
</style> 